package com.lifang.imsoa.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InfoUtils {
	static Logger log = LoggerFactory.getLogger(InfoUtils.class);
	
	static HttpClient httpclient = new DefaultHttpClient();
	static BasicCookieStore cookieStore = new BasicCookieStore();
	static BasicHttpContext httpContext = new BasicHttpContext();
	static{
	    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
	}
	
	public static JSONObject sendRestInter(String url, JSONObject jobj) {
		return sendRest(url, jobj);
	}
	
	public static JSONObject sendRestInter(String url, Map<String, Object> pars) {
		JSONObject jobj = new JSONObject();
		if (pars != null) {
			Iterator<String> iter = pars.keySet().iterator();
			while (iter.hasNext()) {
				String key = iter.next();
				Object value = pars.get(key);
				jobj.put(key, value);
			}
		}
		return sendRest(url, jobj);
	}
	
	private static JSONObject sendRest(String url, JSONObject jobj) {
		String smsUrl=url; 
        HttpPost httppost = new HttpPost(smsUrl);
        //pars.put("App-Key", "fybao.superjia.com");
		//pars.put("App-Secret", "MT0VT5EN1FAP7SGA840OBW2DUFJUAB");
        
        httppost.addHeader("App-Key", "fybao.superjia.com");
        httppost.addHeader("App-Secret","MT0VT5EN1FAP7SGA840OBW2DUFJUAB");
        
        String strResult = "";
          
        try {  
	        //nameValuePairs.add(new BasicNameValuePair("msg", getStringFromJson(jobj)));  
	        //httppost.addHeader("Content-type", "application/x-www-form-urlencoded");  
	        //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));  
	        BasicHttpEntity en = new BasicHttpEntity();
	        en.setContentType("application/json");
	        
	        String str = jobj.toString();
	        if(str == null){
	        	str="";
	        }
	        byte[] bytes = str.getBytes();
	        
	        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
	        en.setContent(bis);
	        en.setContentLength(bytes.length);
	        httppost.setEntity(en);
	        
	          
	        JSONObject sobj = null;
	        HttpResponse response = httpclient.execute(httppost,httpContext);  
	        if (response.getStatusLine().getStatusCode() == 200) {
	        	sobj = new JSONObject();
	            /*读返回数据*/  
	            String conResult = EntityUtils.toString(response.getEntity());  
	            sobj = sobj.fromObject(conResult);  
	            strResult=sobj.toString();
	        } else {  
	            String err = response.getStatusLine().getStatusCode()+"";  
	            strResult += "发送失败:"+err;  
	        }
	        String msg = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))+" url:"+url+"\n 参数:"+jobj.toString()+"\n result:"+strResult+"\n";
	        System.out.println(msg);
	        File file =new File("d:/1.txt");
	        FileOutputStream os =new FileOutputStream(file,true);
	        os.write(msg.getBytes());
	        os.close();
	        return sobj;
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;
	}
	 
	 @SuppressWarnings("unused")
	private static String getStringFromJson(JSONObject adata) {
	        StringBuffer sb = new StringBuffer();  
	        sb.append("{");  
	        for(Object key:adata.keySet()){  
	            sb.append("\""+key+"\":\""+adata.get(key)+"\",");  
	        }  
	        String rtn = sb.toString().substring(0, sb.toString().length()-1)+"}";  
	        return rtn;  
	    }  
	 
	 
	 
	 
	public static void main(String[] args) {
		Map<String, Object> pars = new HashMap<String, Object>();
		/**
		 * 当前日程
		 */
		String url = "http://localhost:8000/release/checkHouseIsSell.rest";
		pars.put("buildingName", "3地方");
		pars.put("subEstateId", 16576);
		pars.put("room", "504");
		pars.put("unitName","");

		try {
		    net.sf.json.JSONObject json = InfoUtils.sendRestInter(url, pars);
			System.out.println(json.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
